<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input style="width: 240px; margin-right: 10px" v-model="data.name" prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger"  @click="delBatch">批量删除</el-button>
<!--      <el-button type="info">导入</el-button>-->
<!--      <el-button type="success">导出</el-button>-->
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column label="账号" prop="username"/>
        <el-table-column label="名称" prop="name"/>
        <el-table-column label="性别" prop="sex"/>
        <el-table-column label="工号" prop="no"/>
        <el-table-column label="年龄" prop="age"/>
        <el-table-column label="个人介绍" prop="description" show-overflow-tooltip/>
        <el-table-column label="部门" prop="departmentName"/>
        <el-table-column label="操作" width="120"> <!--编辑操作需要获取行对象，另外:icon后的元素需要手动导入-->
          <template #default="scope"> <!--获取行对象具体数据scope.row-->
            <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle></el-button>
            <el-button @click="del(scope.row.id)" type="danger" :icon="Delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 15px">
<!--        新增@current-change事件，重新加载分页（可以让其分页）
            新增@size-change事件，可以选择一页展示多少个数据-->
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>

    <el-dialog title="员工信息" v-model="data.formVisible"  width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding-right: 40px;padding-top: 20px"> <!--ref表示表单校验-->
        <el-form-item label="账号" prop="username">
          <el-input v-model="data.form.username" autocomplete="off" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="data.form.sex">
            <el-radio value="男" label="男"></el-radio>
            <el-radio value="女" label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工号" prop="no">
          <el-input v-model="data.form.no" autocomplete="off" placeholder="请输入工号"/>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number style="width: 180px" :min="18" v-model="data.form.age" autocomplete="off" placeholder="请输入年龄"/>
        </el-form-item>
        <el-form-item label="个人介绍">
          <el-input :rows="3" type="textarea" v-model="data.form.description" autocomplete="off" placeholder="请输入个人介绍"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import {reactive,ref} from "vue";
import {Edit,Delete,Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data=reactive({
  name:null,
  tableData:[],
  pageNum:1,
  pageSize:10,
  total:0,
  formVisible:false,
  form:{},
  ids:[],
  rules:{
    username:[
      {required:true, message:'请输入账号', trigger:'blur'}
    ],
    name:[
      {required:true, message:'请输入名称', trigger:'blur'}
    ],
    no:[
      {required:true, message:'请输入工号', trigger:'blur'}
    ]
  }
})

const formRef=ref()

//重置只需要名字清空，然后重新加载一次就行了
const reset=()=>{
  data.name=null
  load()
}

const handleAdd=()=>{
  data.formVisible=true
  data.form = {}
}

const save=()=>{ //因为新增数据是post，修改数据是put，所以一个保存方法需要有两个操作 新增：在保存操作里设置表单校验逻辑
  formRef.value.validate((valid)=>{
    if(valid){
      data.form.id ? update() : add()
    }
  })
}

const add=()=>{
  request.post('employee/add',data.form).then(res=>{ //新增的对象没有id
    if(res.code==='200'){
      data.formVisible=false
      ElMessage.success("操作成功")
      load() //新增后一定要重新加载数据
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const update=()=>{
  request.put('employee/update',data.form).then(res=>{//编辑的对象里包含id
    if(res.code==='200'){
      data.formVisible=false
      ElMessage.success("操作成功")
      load() //更新后一定要重新加载数据
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const handleUpdate=(row)=>{
  data.form=JSON.parse(JSON.stringify(row)) //深拷贝一个新对象用于编辑，这样不会影响行对象
  data.formVisible=true
}

const del=(id)=>{
  ElMessageBox.confirm("删除数据后无法恢复，您确认删除吗？",'删除确认',{type:'warning'}).then(()=>{
    request.delete('employee/deleteById/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("操作成功")
        load() //删除后一定要重新加载数据
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch()
}

const handleSelectionChange=(rows)=>{//返回所有选中的的行对象数组
  //从选中的行数组里取出所有行的id组成一个新的数组
  data.ids=rows.map(row=>row.id)
  console.log(data.ids)
}

const delBatch=()=>{
  if(data.ids.length===0){
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm("删除数据后无法恢复，您确认删除吗？",'删除确认',{type:'warning'}).then(()=>{
    request.delete('employee/deleteBatch',{data:data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success("操作成功")
        load() //删除后一定要重新加载数据
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch()
}

//从后端拿数据
const load=()=>{
  request.get('employee/selectPage',{ //?pageNum=1&pageSize=10
    params:{//params将前端元素与后端数据绑定
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name:data.name
    }
  }).then(res=>{ //res就是后端返回的数据，所有数据都在res.data里面
    data.tableData=res.data.list
    data.total=res.data.total
  })
}

load()
</script>

